#ifndef __CHANNEL_H__
#define __CHANNEL_H__

#include <functional>

using std::function;

class EventLoop;

class Channel
{
public:
    typedef function<void()> EventCallback;
    typedef std::function<void(Timestamp)> ReadEventCallback;

    Channel(EventLoop *loop, int fd);

    void handleEvent(Timestamp receiveTime); //核心 call by EventLoop:根据_revents触发回调
    // void setReadCallback(const EventCallback &cb)
    void setReadCallback(const ReadEventCallback &cb)
    { _readCallback = cb; }
    void setWriteCallback(const EventCallback &cb)
    { _writeCallback = cb; }
    void setErrorCallback(const EventCallback &cb)
    { _errorCallback = cb; }
    void setCloseCallback(const EventCallback &cb)
    { _closeCallback = cb; }

    int fd() const { return _fd; }
    int events() const { return _events; }
    void set_revents(int revents) { _revents = revents; }
    bool isNoneEvent() const { return _revents == kNoneEvent; }

    void enableReading() { _events |= kReadEvent; update(); }
    void disableAll() { _events = kNoneEvent; update(); }

    //for Poller
    int index() const { return _index; }
    void set_index(int index) { _index = index; }

    EventLoop *ownerLoop() { return _loop; }
    void remove();
private:
    void update();

    static const int kNoneEvent;
    static const int kReadEvent;
    static const int kWriteEvent;

    EventLoop *_loop; // 所属EventLoop
    const int _fd;    // 负责的fd
    int _events;      // 关注的IO事件 用户设置
    int _revents;     // 目前活动的事件 EventLoop/Poller设置
    int _index;       // Poller:在_pollfds的索引 用来更新channel->fd()在_pollfds的状态

    bool _eventHandling;
    // EventCallback _readCallback;
    ReadEventCallback _readCallback;
    EventCallback _writeCallback;
    EventCallback _errorCallback;
    EventCallback _closeCallback; // 连接关闭回调
};

#endif